/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package forms;

import classes.Conexao;
import java.sql.ResultSet;
import java.util.HashMap;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Rafael
 */
public class FormIniciarAtendimento extends javax.swing.JInternalFrame {

    private String textoPermitido = "01234567890";
    
    /**
     * Creates new form FormIniciartendimento
     */
    public FormIniciarAtendimento() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents()
    {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldSomaTotal = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jComboBoxProdutos = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        jTextFieldQtd = new javax.swing.JTextField(new classes.CaracteresPermitidos(textoPermitido), "", 20);
        jButtonIncluir = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jButtonLimpar = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        jTextFieldVlUnitario = new javax.swing.JTextField();
        jComboBoxComanda = new javax.swing.JComboBox();

        setClosable(true);
        setIconifiable(true);
        setTitle("Iniciar Atendimento");
        addInternalFrameListener(new javax.swing.event.InternalFrameListener()
        {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt)
            {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt)
            {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt)
            {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt)
            {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt)
            {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt)
            {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt)
            {
                formInternalFrameOpened(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel1.setText("DESCRIÇÃO DOS PRODUTOS E SERVIÇOS");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][]
            {

            },
            new String []
            {
                "Quantidade", "Descrição", "R$ Unitário", "R$ Total"
            }
        )
        {
            Class[] types = new Class []
            {
                java.lang.Integer.class, java.lang.String.class, java.lang.Double.class, java.lang.Double.class
            };

            public Class getColumnClass(int columnIndex)
            {
                return types [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel2.setText("VALOR TOTAL R$:");

        jTextFieldSomaTotal.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jTextFieldSomaTotal.setToolTipText("Valor total");
        jTextFieldSomaTotal.setEnabled(false);

        jLabel3.setText("Produto / Serviço:");

        jComboBoxProdutos.setToolTipText("Selecione o produto ou serviço");
        jComboBoxProdutos.addItemListener(new java.awt.event.ItemListener()
        {
            public void itemStateChanged(java.awt.event.ItemEvent evt)
            {
                jComboBoxProdutosItemStateChanged(evt);
            }
        });

        jLabel4.setText("Quantidade:");

        jTextFieldQtd.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jTextFieldQtd.setToolTipText("Digite a quantidade");

        jButtonIncluir.setText("Incluir");
        jButtonIncluir.setToolTipText("Clique aqui para incluir");
        jButtonIncluir.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButtonIncluirActionPerformed(evt);
            }
        });

        jLabel5.setText("Nº Comanda:");

        jButtonLimpar.setText("Limpar");
        jButtonLimpar.setToolTipText("Clique aqui para limpar os valores");
        jButtonLimpar.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButtonLimparActionPerformed(evt);
            }
        });

        jLabel6.setText("R$ Unitário:");

        jTextFieldVlUnitario.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jTextFieldVlUnitario.setEnabled(false);

        jComboBoxComanda.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGap(0, 159, Short.MAX_VALUE)
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jTextFieldSomaTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(36, 36, 36)
                                        .addComponent(jLabel1))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addComponent(jLabel5)
                                            .addComponent(jLabel6)
                                            .addComponent(jLabel4))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addComponent(jComboBoxProdutos, 0, 145, Short.MAX_VALUE)
                                            .addComponent(jTextFieldVlUnitario)
                                            .addComponent(jTextFieldQtd)
                                            .addComponent(jComboBoxComanda, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(148, 148, 148)
                                        .addComponent(jButtonIncluir)))
                                .addGap(0, 43, Short.MAX_VALUE)))
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButtonLimpar)
                        .addGap(173, 173, 173))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jComboBoxComanda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jComboBoxProdutos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jTextFieldVlUnitario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextFieldQtd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButtonIncluir)
                .addGap(18, 18, 18)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextFieldSomaTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jButtonLimpar)
                .addContainerGap(59, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-410)/2, (screenSize.height-464)/2, 410, 464);
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonIncluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonIncluirActionPerformed
        try {
            //CARREGA A TABELA
            //Pega o valor unitário e guarda
            Double vlu = Double.parseDouble(jTextFieldVlUnitario.getText());
            //Calcula o valor total e guarda na variável
            Double vlt = (Double.parseDouble(jTextFieldQtd.getText()) * vlu);
            //Pega a quantidade
            int qtd = Integer.parseInt(jTextFieldQtd.getText());
            DefaultTableModel modelTable = (DefaultTableModel) jTable1.getModel();
            modelTable.addRow(new Object[]{
                        qtd,
                        jComboBoxProdutos.getSelectedItem().toString(),
                        vlu,
                        vlt
                    });

            //Varre a coluna do valor total, incrementando na variável
            Double valorTotal = 0.00;
            for (int row = 0; row < modelTable.getRowCount(); row++) {
                valorTotal += Double.parseDouble(modelTable.getValueAt(row, 3).toString());
            }
            jTextFieldSomaTotal.setText(valorTotal.toString());

            //SALVA NO BANCO
            String nome = jComboBoxProdutos.getSelectedItem().toString();
            int cd_abertura = comandas.get(jComboBoxComanda.getSelectedItem());
            String sql = "INSERT INTO ATENDIMENTO VALUES (atendimento_seq.nextval," + qtd + ",null," + vlt + ",'" + nome + "',null," + cd_abertura + " )";
            if (Conexao.consultar(sql) == null) {
                JOptionPane.showMessageDialog(null, "Erro ao Inserir no Banco! " + Conexao.getErro());
            }

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Erro:\n" + e.getMessage(), "Aviso", 2);
        }
    }//GEN-LAST:event_jButtonIncluirActionPerformed

    private void jButtonLimparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLimparActionPerformed
        limpar();
    }//GEN-LAST:event_jButtonLimparActionPerformed
    private HashMap<Integer, Integer> comandas = new HashMap<Integer, Integer>();

    private void formInternalFrameOpened(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameOpened
        try {

            //Pega o código de abertura comanda na tabela Abertura Comanda
            String sqlAbertComa =
                    "SELECT \"ABERTURA_COMANDA\".\"cd_abertura_comanda\", \"ABERTURA_COMANDA\".\"cd_comanda\" "
                    + "FROM snooker.\"ABERTURA_COMANDA\" "
                    + "WHERE \"ABERTURA_COMANDA\".\"dt_hora_fechar\" is null "
                    + "ORDER BY \"ABERTURA_COMANDA\".\"cd_comanda\"";
            ResultSet rs1 = Conexao.consultar(sqlAbertComa);
            DefaultComboBoxModel model2 = (DefaultComboBoxModel) jComboBoxComanda.getModel();
            model2.removeAllElements();

            comandas.clear();
            while (rs1.next()) {
                comandas.put(rs1.getInt("cd_comanda"), rs1.getInt("cd_abertura_comanda"));
                model2.addElement(rs1.getInt("cd_comanda"));
            }

            //Carrega o combo com o nome dos produtos
            DefaultComboBoxModel model = (DefaultComboBoxModel) jComboBoxProdutos.getModel();
            // model.removeAllElements();

            String sql = "SELECT * FROM PRODUTO";

            ResultSet rs2 = Conexao.consultar(sql);
            while (rs2.next()) {
                model.addElement(rs2.getString("NM_PRODUTO"));
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Erro:\n" + e.getMessage(), "Aviso", 2);
        }
    }//GEN-LAST:event_formInternalFrameOpened

    private void jComboBoxProdutosItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBoxProdutosItemStateChanged
        try {
            String produto = jComboBoxProdutos.getSelectedItem().toString();
            Double vl_produto = 0.0;
            String sql = "SELECT * FROM PRODUTO WHERE NM_PRODUTO='" + produto + "'";
            ResultSet rs = Conexao.consultar(sql);
            while (rs.next()) {
                vl_produto = rs.getDouble("VL_PRODUTO");
            }
            jTextFieldVlUnitario.setText(vl_produto.toString());
            jTextFieldQtd.setText("");
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Erro: " + e.getMessage());
        }
    }//GEN-LAST:event_jComboBoxProdutosItemStateChanged
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonIncluir;
    private javax.swing.JButton jButtonLimpar;
    private javax.swing.JComboBox jComboBoxComanda;
    private javax.swing.JComboBox jComboBoxProdutos;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextFieldQtd;
    private javax.swing.JTextField jTextFieldSomaTotal;
    private javax.swing.JTextField jTextFieldVlUnitario;
    // End of variables declaration//GEN-END:variables

    private void limpar() {
        //Zera tudo
        jComboBoxComanda.setSelectedIndex(0);
        jComboBoxProdutos.setSelectedIndex(0);
        jTextFieldVlUnitario.setText("");
        jTextFieldQtd.setText("");
        DefaultTableModel modelTable = (DefaultTableModel) jTable1.getModel();
        modelTable.setRowCount(0);
        jTextFieldSomaTotal.setText("");
    }
}
